package com.cn.why.springclouduser_server.controller;

import com.cn.why.springclouduser_server.entity.User;
import com.cn.why.springclouduser_server.service.UserService;
import com.cn.why.springclouduser_server.until.Result;
import com.cn.why.springclouduser_server.until.SingleLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * 用户控制层
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 跳转到登录页面
     * @return
     */
    @RequestMapping(value = "/")
    public String jumpToLogin(){
        return "redirect:/user/checkLogin";
    }
    //登录验证
    @RequestMapping(value = "/checkLogin")
    @ResponseBody
    public Result checkLogin(User user, HttpSession session){
        //定义返回参数
        if (userService.login(user)){
            //添加用户sesesion
            session.setAttribute("user",userService.getUser(user));
            return Result.success((User)(session.getAttribute("user")));//返回200验证成功
        }else{
            return Result.error(null);//返回100验证失败
        }
    }

    /**
     * 跳转到登录页面
     * @return
     */
    @RequestMapping("/login")
    public String login(){
        return "/html/login.html";
    }

    /**
     * 单点登录判断是否在线
     * @param session
     * @return
     */
    @RequestMapping("/isOnline")
    @ResponseBody
    public Result isOnline(HttpSession session){
        //调用判断session用户是否在线
        System.out.println("--------------------------------");
        return Result.success(SingleLogin.isOnline(session));
    }

    /**
     * 单点登录判断用户是否已经登录过
     * @param session
     * @return
     */
    @RequestMapping("isAlreadyLogin")
    @ResponseBody
    public Result isAlreadyLogin(HttpSession session,String userName){
        //调用判断session用户是否在线
        return Result.success(SingleLogin.isAlreadyLogin(session,userName));
    }
}
